package com.tca.common.web.filter;

import com.alibaba.fastjson.JSONObject;
import com.tca.common.core.bean.DataScope;
import com.tca.common.core.constant.CommonConstants;
import com.tca.common.core.datapermission.DataPermissionContextHolder;
import com.tca.common.core.utils.ValidateUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhoua
 * @date 2022/2/14
 */
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
public class DataPermissionContextHolderFilter extends GenericFilterBean {
    
    private DataPermissionContextHolder dataPermissionContextHolder;
    
    public DataPermissionContextHolderFilter(DataPermissionContextHolder dataPermissionContextHolder) {
        this.dataPermissionContextHolder = dataPermissionContextHolder;
    }
    
    @Override
    @SneakyThrows
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        DataScope dataScope;
        // 从 header 或 attribute 中获取 dataScope
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        
        Object attribute = request.getAttribute(CommonConstants.DATA_SCOPE);
        if(attribute == null) {
            String dataScopeStr = request.getHeader(CommonConstants.DATA_SCOPE);
            if (ValidateUtils.isEmpty(dataScopeStr)) {
                dataScope = DataScope.newAllDataScope(null, null);
            } else {
                dataScope = JSONObject.parseObject(dataScopeStr, DataScope.class);
            }
        } else {
            dataScope = JSONObject.parseObject((String)attribute, DataScope.class);
        }
        
        log.debug("filter 获取header中的 dataScope 为 --> {}", JSONObject.toJSONString(dataScope));
        // 设置 dataScope
        dataPermissionContextHolder.setDataScope(dataScope);
        
        try {
            filterChain.doFilter(request, response);
        } finally {
            // 最终清除 dataScope！
            dataPermissionContextHolder.clearDataScope();
        }
    }

}
